package scatter.message.rest.service.impl;

import lombok.extern.slf4j.Slf4j;
import scatter.message.pojo.po.Message;
import scatter.message.pojo.po.MessageUserState;
import scatter.message.rest.mapper.MessageUserStateMapper;
import scatter.message.rest.service.IMessageUserStateService;
import scatter.common.rest.service.IBaseAddUpdateQueryFormServiceImpl;
import org.springframework.stereotype.Service;
import scatter.message.pojo.form.MessageUserStateAddForm;
import scatter.message.pojo.form.MessageUserStateUpdateForm;
import scatter.message.pojo.form.MessageUserStatePageQueryForm;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户消息读取状态表 服务实现类
 * </p>
 *
 * @author yw
 * @since 2021-08-11
 */
@Slf4j
@Service
@Transactional
public class MessageUserStateServiceImpl extends IBaseAddUpdateQueryFormServiceImpl<MessageUserStateMapper, MessageUserState, MessageUserStateAddForm, MessageUserStateUpdateForm, MessageUserStatePageQueryForm> implements IMessageUserStateService {
    @Override
    public void preAdd(MessageUserStateAddForm addForm,MessageUserState po) {
        super.preAdd(addForm,po);

    }

    @Override
    public void preUpdate(MessageUserStateUpdateForm updateForm,MessageUserState po) {
        super.preUpdate(updateForm,po);

    }

    @Override
    public List<MessageUserState> sendMessageByUserIds(Message message, List<String> userIdsList, boolean checkHasUserIds) {

        if (isEmpty(userIdsList)) {
            return null;
        }
        // 从数据库中查询数据库中已经存在的
        List<String> dbExistUserIds = new ArrayList<>(userIdsList.size());
        if(checkHasUserIds){
            List<MessageUserState> dbExist = getByMessageIdAndUserIds(message.getId(),userIdsList);
            if (!isEmpty(dbExist)) {
                dbExistUserIds.addAll(dbExist.stream().map(MessageUserState::getUserId).collect(Collectors.toList()));
            }
        }

        List<MessageUserState> userStates = userIdsList.stream()
                .filter(userId -> !dbExistUserIds.contains(userId))
                .map(userId -> {
            MessageUserState messageUserState = new MessageUserState();
            messageUserState.setMessageId(message.getId());
            messageUserState.setIsRead(false);
            messageUserState.setUserId(userId);
            return messageUserState;
        }).collect(Collectors.toList());

        if (isEmpty(userStates)) {
            log.warn("没有需要发送的消息了，可能已经被发送完成，messageId={},title={}",message.getId(),message.getTitle());
            return null;
        }

        boolean b = saveBatch(userStates);
        if (!b) {
            log.error("消息入库失败，messageId={},title={}",message.getId(),message.getTitle());
            return null;
        }


        // 批量插入成功，已经包含id
        return userStates;
    }
}
